import React, { useRef, useMemo } from 'react';
import { useFrame } from '@react-three/fiber';
import { Box, Cylinder, Sphere, RoundedBox, Torus } from '@react-three/drei';
import * as THREE from 'three';

const Drone = ({
  animationSpeed = 1,
  showComponents = {
    frame: true,
    rotors: true,
    camera: true,
    landingGear: true,
    lights: true
  },
  colors = {
    frame: '#2c3e50',
    rotors: '#34495e',
    camera: '#1a1a1a',
    lights: '#e74c3c'
  },
  flightState = null
}) => {
  const droneRef = useRef();
  const rotorRefs = useRef([]);

  // Animation
  useFrame((state, delta) => {
    // Rotate propellers
    const propellerSpeed = flightState?.isFlying ? animationSpeed * 20 : animationSpeed * 5;
    rotorRefs.current.forEach((rotor) => {
      if (rotor) {
        rotor.rotation.y += delta * propellerSpeed;
      }
    });

    // Update drone position and rotation from flight controller
    if (droneRef.current && flightState) {
      droneRef.current.position.copy(flightState.position);
      droneRef.current.rotation.copy(flightState.rotation);
    } else if (droneRef.current) {
      // Default gentle floating animation when no flight controller
      droneRef.current.position.y = Math.sin(state.clock.elapsedTime * 0.5) * 0.1 + 2;
      droneRef.current.rotation.z = Math.sin(state.clock.elapsedTime * 0.3) * 0.02;
    }
  });

  // Rotor positions for quadcopter - reduced proportions
  const rotorPositions = useMemo(() => [
    [0.8, 0.08, 0.8],   // Front right
    [-0.8, 0.08, 0.8],  // Front left
    [0.8, 0.08, -0.8],  // Back right
    [-0.8, 0.08, -0.8]  // Back left
  ], []);

  return (
    <group ref={droneRef}>
      {/* Enhanced Main Frame */}
      {showComponents.frame && (
        <group>
          {/* Central body - compact and sleek design */}
          <RoundedBox args={[0.6, 0.25, 0.6]} radius={0.04} smoothness={4} position={[0, 0, 0]}>
            <meshStandardMaterial
              color={colors.frame}
              metalness={0.8}
              roughness={0.2}
              envMapIntensity={1.2}
            />
          </RoundedBox>

          {/* Top cover with carbon fiber pattern */}
          <RoundedBox args={[0.58, 0.015, 0.58]} radius={0.015} smoothness={4} position={[0, 0.13, 0]}>
            <meshStandardMaterial
              color="#0a0a0a"
              metalness={0.95}
              roughness={0.05}
              envMapIntensity={2}
            />
          </RoundedBox>

          {/* GPS/Communication antenna */}
          <Cylinder args={[0.008, 0.008, 0.08]} position={[0.15, 0.18, -0.15]}>
            <meshStandardMaterial
              color="#2c3e50"
              metalness={0.9}
              roughness={0.1}
            />
          </Cylinder>
          <Sphere args={[0.012]} position={[0.15, 0.22, -0.15]}>
            <meshStandardMaterial
              color="#34495e"
              metalness={0.8}
              roughness={0.2}
            />
          </Sphere>

          {/* Battery indicator LED */}
          <Sphere args={[0.008]} position={[0, 0.14, -0.25]}>
            <meshStandardMaterial
              color="#00ff00"
              emissive="#00ff00"
              emissiveIntensity={flightState?.isFlying ? 0.6 : 0.3}
            />
          </Sphere>

          {/* Ventilation grilles */}
          {[-0.2, -0.1, 0, 0.1, 0.2].map((x, index) => (
            <Box key={`vent-${index}`} args={[0.02, 0.005, 0.15]} position={[x, 0.125, 0]}>
              <meshStandardMaterial
                color="#1a1a1a"
                metalness={0.7}
                roughness={0.3}
              />
            </Box>
          ))}

          {/* Enhanced Arms with better geometry - more compact */}
          <RoundedBox args={[1.9, 0.08, 0.08]} radius={0.02} smoothness={4} position={[0, 0, 0.85]}>
            <meshStandardMaterial
              color={colors.frame}
              metalness={0.7}
              roughness={0.3}
              envMapIntensity={1}
            />
          </RoundedBox>
          <RoundedBox args={[1.9, 0.08, 0.08]} radius={0.02} smoothness={4} position={[0, 0, -0.85]}>
            <meshStandardMaterial
              color={colors.frame}
              metalness={0.7}
              roughness={0.3}
              envMapIntensity={1}
            />
          </RoundedBox>
          <RoundedBox args={[0.08, 0.08, 1.9]} radius={0.02} smoothness={4} position={[0.85, 0, 0]}>
            <meshStandardMaterial
              color={colors.frame}
              metalness={0.7}
              roughness={0.3}
              envMapIntensity={1}
            />
          </RoundedBox>
          <RoundedBox args={[0.08, 0.08, 1.9]} radius={0.02} smoothness={4} position={[-0.85, 0, 0]}>
            <meshStandardMaterial
              color={colors.frame}
              metalness={0.7}
              roughness={0.3}
              envMapIntensity={1}
            />
          </RoundedBox>

          {/* Motor mounts at arm ends - more compact */}
          {rotorPositions.map((position, index) => (
            <Cylinder key={`mount-${index}`} args={[0.12, 0.1, 0.06]} position={[position[0], position[1] - 0.03, position[2]]}>
              <meshStandardMaterial
                color="#34495e"
                metalness={0.85}
                roughness={0.15}
                envMapIntensity={1.3}
              />
            </Cylinder>
          ))}
        </group>
      )}

      {/* Optimized Rotors and Propellers */}
      {showComponents.rotors && rotorPositions.map((position, index) => (
        <group key={index} position={position}>
          {/* Compact Motor with heat sink design */}
          <Cylinder args={[0.11, 0.09, 0.18]} position={[0, 0, 0]}>
            <meshStandardMaterial
              color={colors.rotors}
              metalness={0.85}
              roughness={0.15}
              envMapIntensity={1.4}
            />
          </Cylinder>

          {/* Motor cooling fins - smaller and more refined */}
          {[0, 1, 2, 3, 4, 5].map((finIndex) => (
            <Box
              key={`fin-${finIndex}`}
              args={[0.015, 0.18, 0.008]}
              position={[
                Math.cos(finIndex * Math.PI / 3) * 0.12,
                0,
                Math.sin(finIndex * Math.PI / 3) * 0.12
              ]}
            >
              <meshStandardMaterial
                color="#2c3e50"
                metalness={0.8}
                roughness={0.2}
              />
            </Box>
          ))}

          {/* Motor top cap */}
          <Cylinder args={[0.08, 0.08, 0.02]} position={[0, 0.1, 0]}>
            <meshStandardMaterial
              color="#0a0a0a"
              metalness={0.95}
              roughness={0.05}
            />
          </Cylinder>

          {/* Optimized Propeller with realistic design */}
          <group ref={(el) => rotorRefs.current[index] = el}>
            {/* Propeller hub - more compact */}
            <Cylinder args={[0.03, 0.03, 0.015]} position={[0, 0.12, 0]}>
              <meshStandardMaterial
                color="#2c3e50"
                metalness={0.9}
                roughness={0.1}
              />
            </Cylinder>

            {/* Propeller blades - sleeker design with better proportions */}
            {[0, 1].map((bladeIndex) => (
              <group key={`blade-${bladeIndex}`} rotation={[0, bladeIndex * Math.PI, 0]}>
                {/* Main blade - more realistic shape */}
                <Box args={[0.015, 0.006, 0.6]} position={[0, 0.12, 0.25]}>
                  <meshStandardMaterial
                    color="#bdc3c7"
                    metalness={0.4}
                    roughness={0.6}
                    transparent
                    opacity={0.95}
                  />
                </Box>
                {/* Blade tip - aerodynamic */}
                <Sphere args={[0.01]} position={[0, 0.12, 0.55]}>
                  <meshStandardMaterial
                    color="#95a5a6"
                    metalness={0.5}
                    roughness={0.5}
                  />
                </Sphere>
                {/* Blade root reinforcement */}
                <Box args={[0.02, 0.008, 0.08]} position={[0, 0.12, 0.04]}>
                  <meshStandardMaterial
                    color="#34495e"
                    metalness={0.7}
                    roughness={0.3}
                  />
                </Box>
                {/* Blade twist for realism */}
                <Box args={[0.012, 0.004, 0.15]} position={[0, 0.12, 0.4]} rotation={[0, 0, 0.1]}>
                  <meshStandardMaterial
                    color="#bdc3c7"
                    metalness={0.4}
                    roughness={0.6}
                    transparent
                    opacity={0.9}
                  />
                </Box>
              </group>
            ))}

            {/* Propeller motion blur effect when spinning fast */}
            {flightState?.isFlying && (
              <Torus args={[0.28, 0.008, 8, 32]} position={[0, 0.12, 0]} rotation={[Math.PI / 2, 0, 0]}>
                <meshStandardMaterial
                  color="#bdc3c7"
                  transparent
                  opacity={0.15}
                  metalness={0.3}
                  roughness={0.7}
                />
              </Torus>
            )}
          </group>
        </group>
      ))}

      {/* Optimized Camera Gimbal */}
      {showComponents.camera && (
        <group position={[0, -0.2, 0.25]}>
          {/* Gimbal mounting bracket - more compact */}
          <Box args={[0.2, 0.03, 0.06]} position={[0, 0.1, -0.06]}>
            <meshStandardMaterial
              color="#2c3e50"
              metalness={0.85}
              roughness={0.15}
            />
          </Box>

          {/* Gimbal outer ring - smaller */}
          <Torus args={[0.12, 0.015, 8, 32]} position={[0, 0, 0]} rotation={[0, 0, 0]}>
            <meshStandardMaterial
              color={colors.camera}
              metalness={0.8}
              roughness={0.2}
            />
          </Torus>

          {/* Gimbal inner ring - smaller */}
          <Torus args={[0.1, 0.01, 8, 32]} position={[0, 0, 0]} rotation={[Math.PI / 2, 0, 0]}>
            <meshStandardMaterial
              color={colors.camera}
              metalness={0.8}
              roughness={0.2}
            />
          </Torus>

          {/* Camera body - more compact and sleek */}
          <RoundedBox args={[0.18, 0.1, 0.08]} radius={0.015} smoothness={4} position={[0, 0, 0]}>
            <meshStandardMaterial
              color="#0a0a0a"
              metalness={0.7}
              roughness={0.3}
            />
          </RoundedBox>

          {/* Camera lens assembly - more compact */}
          <Cylinder args={[0.06, 0.05, 0.12]} position={[0, 0, 0.1]} rotation={[Math.PI / 2, 0, 0]}>
            <meshStandardMaterial
              color="#2c3e50"
              metalness={0.85}
              roughness={0.15}
            />
          </Cylinder>

          {/* Lens glass with realistic reflection */}
          <Cylinder args={[0.045, 0.045, 0.02]} position={[0, 0, 0.16]} rotation={[Math.PI / 2, 0, 0]}>
            <meshStandardMaterial
              color="#001122"
              transparent
              opacity={0.95}
              metalness={0.05}
              roughness={0.0}
              envMapIntensity={2.5}
            />
          </Cylinder>

          {/* Lens hood - smaller */}
          <Cylinder args={[0.055, 0.05, 0.03]} position={[0, 0, 0.18]} rotation={[Math.PI / 2, 0, 0]}>
            <meshStandardMaterial
              color="#0a0a0a"
              metalness={0.4}
              roughness={0.7}
            />
          </Cylinder>

          {/* Camera status LED - smaller */}
          <Sphere args={[0.006]} position={[0.06, 0.03, 0.03]}>
            <meshStandardMaterial
              color="#ff0000"
              emissive="#ff0000"
              emissiveIntensity={flightState?.isFlying ? 1.0 : 0.3}
            />
          </Sphere>

          {/* Gimbal servo motors - more compact */}
          <Cylinder args={[0.02, 0.02, 0.04]} position={[0.08, 0, 0]} rotation={[0, 0, Math.PI / 2]}>
            <meshStandardMaterial
              color="#34495e"
              metalness={0.8}
              roughness={0.2}
            />
          </Cylinder>
          <Cylinder args={[0.02, 0.02, 0.04]} position={[0, 0.08, 0]} rotation={[Math.PI / 2, 0, 0]}>
            <meshStandardMaterial
              color="#34495e"
              metalness={0.8}
              roughness={0.2}
            />
          </Cylinder>
        </group>
      )}

      {/* Optimized Landing Gear */}
      {showComponents.landingGear && (
        <group>
          {/* Landing legs - more compact and sleek */}
          <Cylinder args={[0.015, 0.015, 0.25]} position={[0.4, -0.25, 0.4]}>
            <meshStandardMaterial
              color="#7f8c8d"
              metalness={0.6}
              roughness={0.4}
            />
          </Cylinder>
          <Cylinder args={[0.015, 0.015, 0.25]} position={[-0.4, -0.25, 0.4]}>
            <meshStandardMaterial
              color="#7f8c8d"
              metalness={0.6}
              roughness={0.4}
            />
          </Cylinder>
          <Cylinder args={[0.015, 0.015, 0.25]} position={[0.4, -0.25, -0.4]}>
            <meshStandardMaterial
              color="#7f8c8d"
              metalness={0.6}
              roughness={0.4}
            />
          </Cylinder>
          <Cylinder args={[0.015, 0.015, 0.25]} position={[-0.4, -0.25, -0.4]}>
            <meshStandardMaterial
              color="#7f8c8d"
              metalness={0.6}
              roughness={0.4}
            />
          </Cylinder>

          {/* Landing pads - more realistic design */}
          <Cylinder args={[0.03, 0.03, 0.02]} position={[0.4, -0.38, 0.4]}>
            <meshStandardMaterial
              color="#34495e"
              metalness={0.7}
              roughness={0.3}
            />
          </Cylinder>
          <Cylinder args={[0.03, 0.03, 0.02]} position={[-0.4, -0.38, 0.4]}>
            <meshStandardMaterial
              color="#34495e"
              metalness={0.7}
              roughness={0.3}
            />
          </Cylinder>
          <Cylinder args={[0.03, 0.03, 0.02]} position={[0.4, -0.38, -0.4]}>
            <meshStandardMaterial
              color="#34495e"
              metalness={0.7}
              roughness={0.3}
            />
          </Cylinder>
          <Cylinder args={[0.03, 0.03, 0.02]} position={[-0.4, -0.38, -0.4]}>
            <meshStandardMaterial
              color="#34495e"
              metalness={0.7}
              roughness={0.3}
            />
          </Cylinder>
        </group>
      )}

      {/* Optimized LED Lights */}
      {showComponents.lights && (
        <group>
          {/* Front navigation lights (white) - more compact */}
          <group position={[0, 0.04, 0.32]}>
            <Sphere args={[0.025]}>
              <meshStandardMaterial
                color="#ffffff"
                emissive="#ffffff"
                emissiveIntensity={flightState?.isFlying ? 1.2 : 0.4}
                transparent
                opacity={0.95}
              />
            </Sphere>
            {/* Light housing - smaller */}
            <Cylinder args={[0.03, 0.03, 0.015]} position={[0, 0, -0.015]}>
              <meshStandardMaterial
                color="#2c3e50"
                metalness={0.85}
                roughness={0.15}
              />
            </Cylinder>
          </group>

          {/* Rear navigation lights (red) - more compact */}
          <group position={[0, 0.04, -0.32]}>
            <Sphere args={[0.025]}>
              <meshStandardMaterial
                color={colors.lights}
                emissive={colors.lights}
                emissiveIntensity={flightState?.isFlying ? 1.2 : 0.4}
                transparent
                opacity={0.95}
              />
            </Sphere>
            {/* Light housing - smaller */}
            <Cylinder args={[0.03, 0.03, 0.015]} position={[0, 0, 0.015]}>
              <meshStandardMaterial
                color="#2c3e50"
                metalness={0.85}
                roughness={0.15}
              />
            </Cylinder>
          </group>

          {/* Side strobe lights (green/red) - more compact */}
          <group position={[0.32, 0.04, 0]}>
            <Sphere args={[0.018]}>
              <meshStandardMaterial
                color="#00ff00"
                emissive="#00ff00"
                emissiveIntensity={flightState?.isFlying ? 1.0 : 0.3}
                transparent
                opacity={0.9}
              />
            </Sphere>
            <Cylinder args={[0.022, 0.022, 0.01]} position={[0, 0, 0]}>
              <meshStandardMaterial
                color="#0a0a0a"
                metalness={0.8}
                roughness={0.2}
              />
            </Cylinder>
          </group>

          <group position={[-0.32, 0.04, 0]}>
            <Sphere args={[0.018]}>
              <meshStandardMaterial
                color="#ff0000"
                emissive="#ff0000"
                emissiveIntensity={flightState?.isFlying ? 1.0 : 0.3}
                transparent
                opacity={0.9}
              />
            </Sphere>
            <Cylinder args={[0.022, 0.022, 0.01]} position={[0, 0, 0]}>
              <meshStandardMaterial
                color="#0a0a0a"
                metalness={0.8}
                roughness={0.2}
              />
            </Cylinder>
          </group>

          {/* Bottom status LED strip - more compact */}
          <RoundedBox args={[0.4, 0.008, 0.02]} radius={0.004} smoothness={4} position={[0, -0.13, 0]}>
            <meshStandardMaterial
              color="#0080ff"
              emissive="#0080ff"
              emissiveIntensity={flightState?.isFlying ? 0.8 : 0.2}
              transparent
              opacity={0.8}
            />
          </RoundedBox>

          {/* Arm tip lights - smaller */}
          {rotorPositions.map((position, index) => (
            <Sphere
              key={`arm-light-${index}`}
              args={[0.01]}
              position={[position[0], position[1] - 0.06, position[2]]}
            >
              <meshStandardMaterial
                color="#ffffff"
                emissive="#ffffff"
                emissiveIntensity={flightState?.isFlying ? 0.6 : 0.2}
                transparent
                opacity={0.8}
              />
            </Sphere>
          ))}
        </group>
      )}
    </group>
  );
};

export default Drone;
